package com.photoeditor.demo.ui.widget.image.edit;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.android.graffiti.BrushWidthRadioButton;
import com.android.graffiti.BrushWidthRadioButtonOld;
import com.android.graffiti.BrushesPopupView;
import com.android.graffiti.ColorRadioButton;
import com.android.graffiti.GraffitoView;
import com.android.graffiti.SelectorPopupView;
import com.photoeditor.R;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.ui.widget.CheckableImageView;


public class DoodleBarView extends LinearLayout implements IDealInit {

    // 涂鸦画板的视图
    private GraffitoView mGraffitoView;

    // 涂鸦界面的按钮res
    private CustomTabButton mGftBrushesButton;
    private CustomTabButton mGftEraserButton;
    private CustomTabButton mGftUndoButton;
    private CustomTabButton mGftResetButton;

    // 弹出框
    private BrushesPopupView mBrushesPopupView;
    private SelectorPopupView mEraserPopupView;

    // 当前的状态值
    private int mCurrentBrushType = GraffitoView.BRUSH_TYPE_DEFAULT;

    private Animation mAnimationIn;
    private Animation mAnimationOut;

    private CheckableImageView mGftBrushesButtonBg;
    private CheckableImageView mGftEraserButtonBg;

    private boolean mHasMosaic = true;

    private boolean mSaveStatus = false;

    public void setSaveStatus(boolean saveStatus) {
        mSaveStatus = saveStatus;
    }

    public void setHasMosaic(boolean hasMosaic) {
        mHasMosaic = hasMosaic;
    }

    public DoodleBarView(Context context) {
        super(context);
    }

    public DoodleBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DoodleBarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    @Override
    public void init() {
        initlizeViews();
        initlizeGraffito();
    }


    public void setGraffitoView(GraffitoView graffitoView) {
        mGraffitoView = graffitoView;
    }

    /**
     * 初始化
     */
    private void initlizeViews() {

        hookupGraffitoButtons();
        importGraffitoIfNeed();

        initView(getResources().getColor(R.color.image_edit_sencond_text_color),
                getResources().getColor(R.color.accent_color));

        setGraffitoAllFunctionEnable(true);
    }


    /**
     * 初始化涂鸦
     */
    private void initlizeGraffito() {
        mGraffitoView.setOnDrawGraffitoListener(
                new GraffitoView.OnDrawGraffitoListener() {

                    @Override
                    public void onStrokeFinish(View v, float x, float y) {
                        if (!mGraffitoView.isEmpty()) {
                            setGraffitoOperateButtonsEnable(true);
                            if (mDoodleBarViewListener != null) {
                                mDoodleBarViewListener.doDraw(true);
                            }
                        } else {
                            setGraffitoOperateButtonsEnable(false);
                            if (mDoodleBarViewListener != null) {
                                mDoodleBarViewListener.doDraw(false);
                            }
                        }
                    }

                    @Override
                    public void onNewStroke(View v, float x, float y) {

                /*if(mGraffitoView.getBrushType() == GraffitoView.BRUSH_TYPE_ERASER) {
                     mGftEraserButton.setChecked(false);
                     mGftEraserButtonBg.setChecked(false);
                }
                else{
                    mGftBrushesButton.setChecked(false);
                    mGftBrushesButtonBg.setChecked(false);
                }*/
                    }

                    @Override
                    public void onNeedClosePopView() {
                        setEraserPopupView(View.GONE);
                        setBrushesPopupView(View.GONE);
                    }
                });
        mGraffitoView.setBrushType(mCurrentBrushType);
    }

    private OnClickListener mClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.graffito_btn_brush) {
                mEraserPopupView.setVisibility(GONE);
                checkBrushButton();

                boolean isNeedReset = false;
                if (mGraffitoView.getBrushType() == GraffitoView.BRUSH_TYPE_ERASER) {
                    mGraffitoView.setBrushType(mCurrentBrushType);
                    isNeedReset = true;
//                    return;  // TODO 此处取消return，意味着按此按钮一定会弹出选择框
                }

                if (isNeedReset) {
                    if (mGraffitoView.getColorType() == 1) {
                        mGraffitoView.setBrushColor(mGraffitoView.getBrushColor());
                    }
                }

                if (mBrushesPopupView.isShown()) {
                    setBrushesPopupView(View.GONE);
                } else {
                    setBrushesPopupView(View.VISIBLE);

                }

            } else if (id == R.id.graffito_btn_eraser) {
                mBrushesPopupView.setVisibility(View.GONE);
                checkEraserButton();

                if (mGraffitoView.getBrushType() != GraffitoView.BRUSH_TYPE_ERASER) {
                    mGraffitoView.setBrushType(GraffitoView.BRUSH_TYPE_ERASER);
                    mGraffitoView.setUsingVipBrush(false);
//                    return;  // TODO 此处取消return，意味着按此按钮一定会弹出选择框
                }

                if (mEraserPopupView.isShown()) {
                    setEraserPopupView(View.GONE);
                } else {
                    setEraserPopupView(View.VISIBLE);
                }
            } else if (id == R.id.graffito_btn_undo) {
                // 撤销上次绘制的线条
                mGraffitoView.undo();
                if (mGraffitoView.isEmpty()) {
                    setGraffitoOperateButtonsEnable(false);
                    if (mDoodleBarViewListener != null) {
                        mDoodleBarViewListener.doDraw(false);
                    }
                } else {
                    setGraffitoOperateButtonsEnable(true);
                }
            } else if (id == R.id.graffito_btn_reset) {
                mGraffitoView.reset(mMosaicType);
                if (mGraffitoView.isEmpty()) {
                    setGraffitoOperateButtonsEnable(false);
                    if (mDoodleBarViewListener != null) {
                        mDoodleBarViewListener.doDraw(false);
                    }
                } else {
                    setGraffitoOperateButtonsEnable(true);
                }
            }

        }
    };

    /**
     * 马赛克标志
     */
    private int mMosaicType;

    public int getMosaicType() {
        return mMosaicType;
    }

    private void hookupGraffitoButtons() {

        mGftBrushesButton = (CustomTabButton) findViewById(R.id.graffito_btn_brush);
        mGftBrushesButton.setOnClickListener(mClickListener);

        mGftEraserButton = (CustomTabButton) findViewById(R.id.graffito_btn_eraser);
        mGftEraserButton.setOnClickListener(mClickListener);

        mGftUndoButton = (CustomTabButton) findViewById(R.id.graffito_btn_undo);
        mGftUndoButton.setOnClickListener(mClickListener);
        mGftUndoButton.setEnabled(false);
        mGftUndoButton.setAlpha(128);

        mGftResetButton = (CustomTabButton) findViewById(R.id.graffito_btn_reset);
        mGftResetButton.setOnClickListener(mClickListener);
        mGftUndoButton.setEnabled(false);
        mGftUndoButton.setAlpha(128);

        mGftBrushesButtonBg = (CheckableImageView) findViewById(R.id.graffito_btn_brush_bg);
        mGftEraserButtonBg = (CheckableImageView) findViewById(R.id.graffito_btn_eraser_bg);

        mBrushesPopupView = (BrushesPopupView) findViewById(R.id.graffito_popup_brushes);
        mBrushesPopupView.setHasMosaic(mHasMosaic);
        mBrushesPopupView.init();

        mBrushesPopupView.setColorCheckedListener(
                new RadioGroup.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        ColorRadioButton button =
                                (ColorRadioButton) group.findViewById(checkedId);
                        final int color = button.getColor();

                        int colorType = button.getType();
                        int resId = button.getImage();
                        if (colorType == GraffitoView.BRUSH_TYPE_CUSTOM) {
                            mGraffitoView.setCustomResource(resId);
                        } else {
                            mGraffitoView.setBrushType(GraffitoView.BRUSH_TYPE_DEFAULT);
                            mGraffitoView.setColorType(colorType);
                            mGraffitoView.setBrushColor(color);
                            mMosaicType = colorType;
                        }

                        mGraffitoView.setUsingVipBrush(isVipBrushResId(checkedId));

                    }
                });
        mBrushesPopupView.setWidthCheckedListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                BrushWidthRadioButtonOld button =
                        (BrushWidthRadioButtonOld) group.findViewById(checkedId);
                float brushWidth = button.getBrushWidth();
                mGraffitoView.setBrushWidth(brushWidth);
            }
        });
        mBrushesPopupView.setWidthButtonChecked(2, true);
        if (mHasMosaic) {
            mBrushesPopupView.setColorButtonChecked(1, true);
        } else {
            mBrushesPopupView.setColorButtonChecked(0, true);
        }

        mEraserPopupView = (SelectorPopupView) findViewById(R.id.graffito_popup_eraser);
        mEraserPopupView.initialize(R.layout.graffito_popup_brush_width);
        mEraserPopupView.setOnRadioCheckedListener(
                new RadioGroup.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        BrushWidthRadioButton button =
                                (BrushWidthRadioButton) group.findViewById(checkedId);
                        float brushWidth = button.getBrushWidth();
                        mGraffitoView.setEraserWidth(brushWidth);
                    }
                });
        mEraserPopupView.setButtonChecked(2, true);

    }

    public static boolean isVipBrushResId(int resId) {
        if (AppVipManager.isVip()) {
            return false;
        }
        return resId == R.id.vip_brush_1 ||
                resId == R.id.vip_brush_2 ||
                resId == R.id.vip_brush_3 ||
                resId == R.id.vip_brush_4 ||
                resId == R.id.vip_brush_5;
    }

    private boolean mGftUndoButtonOriEnable = false;

    /**
     * TODO 设置涂鸦全部功能是否可用，对于原有的设置不变
     *
     * @param enable 涂鸦全部功能是否可用re
     */
    protected void setGraffitoAllFunctionEnable(boolean enable) {
        mGraffitoView.setEnabled(enable);

        mGftBrushesButton.setEnabled(enable);
        mGftEraserButton.setEnabled(enable);

        if (!enable) {
            mGftUndoButtonOriEnable = mGftUndoButton.isEnabled();
        }
        mGftUndoButton.setEnabled(enable && mGftUndoButtonOriEnable);
        mGftResetButton.setEnabled(enable && mGftUndoButtonOriEnable);

        int alpha = enable ? 255 : 128;
        mGftBrushesButton.setAlpha(alpha);
        mGftEraserButton.setAlpha(alpha);


        alpha = (enable && mGftUndoButtonOriEnable) ? 255 : 128;
        mGftUndoButton.setAlpha(alpha);
        mGftResetButton.setAlpha(alpha);

        checkBrushButton();
    }

    /**
     * 设置涂鸦的操作按钮的可用性</br>
     * 目前包括发送、撤销、清空和分享，这些功能都仅画布上面有内容才能使用
     *
     * @param enable 是否可用
     */
    private void setGraffitoOperateButtonsEnable(boolean enable) {
        int alpha = enable ? 255 : 128;

        mGftUndoButton.setEnabled(enable);
        mGftUndoButton.setAlpha(alpha);

        mGftResetButton.setEnabled(enable);
        mGftResetButton.setAlpha(alpha);
    }

    /**
     * 如果Intent中含有需要导入的涂鸦的信息，则导入该涂鸦
     */
    private void importGraffitoIfNeed() {
        // 导入图片到涂鸦画板
        mGraffitoView.setContentPadding(0f);

        mGftUndoButton.setEnabled(true);
        mGftUndoButton.setAlpha(255);
    }

    public void setBrushesPopupView(int visibility) {
        if (mBrushesPopupView.getVisibility() == visibility) return;
        if (visibility == View.VISIBLE) {
            mGraffitoView.setHasPopView(true);
            mBrushesPopupView.setVisibility(visibility);
            mBrushesPopupView.startAnimation(getAnimationIn());
        } else {
            mGraffitoView.setHasPopView(false);
            mBrushesPopupView.startAnimation(getAnimationOut());
            mBrushesPopupView.setVisibility(visibility);
        }
    }

    private void checkBrushButton() {
        mGftBrushesButton.setChecked(true);
        mGftBrushesButtonBg.setChecked(true);
        mGftEraserButton.setChecked(false);
        mGftEraserButtonBg.setChecked(false);
    }

    private void checkEraserButton() {
        mGftBrushesButton.setChecked(false);
        mGftBrushesButtonBg.setChecked(false);
        mGftEraserButton.setChecked(true);
        mGftEraserButtonBg.setChecked(true);
    }

    public View getBrushesPopupView() {
        return mBrushesPopupView;
    }

    public View getEraserPopupView() {
        return mEraserPopupView;
    }

    public void setEraserPopupView(int visibility) {
        if (mEraserPopupView.getVisibility() == visibility) return;
        if (visibility == View.VISIBLE) {
            mGraffitoView.setHasPopView(true);
            mEraserPopupView.setVisibility(visibility);
            mEraserPopupView.startAnimation(getAnimationIn());
        } else {
            mGraffitoView.setHasPopView(false);
            mEraserPopupView.startAnimation(getAnimationOut());
            mEraserPopupView.setVisibility(visibility);
        }
    }

    private Animation getAnimationIn() {
        if (mAnimationIn == null) {
            mAnimationIn = AnimationUtils.loadAnimation(getContext(), R.anim.bottom_in);
        } else {
            mAnimationIn.reset();
        }
        return mAnimationIn;
    }

    private Animation getAnimationOut() {
        if (mAnimationOut == null) {
            mAnimationOut = AnimationUtils.loadAnimation(getContext(), R.anim.bottom_out);
        } else {
            mAnimationOut.reset();
        }
        return mAnimationOut;
    }

    private void clearUi() {
        mGraffitoView = null;

        mGftBrushesButton = null;
        mGftEraserButton = null;
        mGftUndoButton = null;
        mGftResetButton = null;

        mBrushesPopupView = null;
        mEraserPopupView = null;
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        clearUi();
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (!mSaveStatus && (visibility == View.GONE || visibility == View.INVISIBLE)) {
            setGraffitoOperateButtonsEnable(false);
        }

    }

    private boolean mIsFirstUseGraffitiView = true;

    public void setGraffitiBitmap(Bitmap bitmap) {
        if (mGraffitoView != null && bitmap != null) {
            if (mIsFirstUseGraffitiView) {
                mGraffitoView.setExtraBitmap(bitmap, true);
                mIsFirstUseGraffitiView = false;
            } else {
                mGraffitoView.updateExtraBitmap(bitmap);
            }
            mGraffitoView.setEnabled(true);
        }
    }

    public void initView(int primaryColor, int emphasisColor) {

        mGftBrushesButton.setThemeImageRes(R.drawable.ic_tool_doodle_paint,
                R.drawable.ic_tool_doodle_paint_light);
        mGftBrushesButton.setTextColor(primaryColor, emphasisColor);
        mGftEraserButton.setThemeImageRes(R.drawable.ic_tool_doodle_rerser,
                R.drawable.ic_tool_doodle_rerser_light);
        mGftEraserButton.setTextColor(primaryColor, emphasisColor);

        mGftUndoButton.setThemeImageRes(R.drawable.ic_tool_doodle_undo, View.NO_ID);
        mGftUndoButton.setTextColor(primaryColor, primaryColor);

        mGftResetButton.setThemeImageRes(R.drawable.ic_tool_doodle_refresh, View.NO_ID);
        mGftResetButton.setTextColor(primaryColor, primaryColor);

    }

    private DoodleBarViewListener mDoodleBarViewListener;

    public void setDoodleBarViewListener(DoodleBarViewListener doodleBarViewListener) {
        mDoodleBarViewListener = doodleBarViewListener;
    }

    public interface DoodleBarViewListener {
        void doDraw(boolean yes);
    }
}
